<?php

namespace App\Http\Controllers;

use App\Exports\HumidityExport;
use App\Imports\ArchiveManageVolumeImport;
use App\Imports\DocArchiveImport;
use App\Imports\HumidityImport;
use App\Models\ArchiveManage;
use App\Models\ArchiveManageVolume;
use App\Models\Humidity;
use App\Models\Menu;
use App\Models\Project;
use App\Services\ArchiveManageService;
use App\Services\CommonService;
use App\Services\DownloadJobService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class HumidityController extends Controller
{
    /**
     * 获取仓库列表
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-29 9:09
     */
    public function getList(Request $request): JsonResponse
    {
        $projectId  = $request->input('project_id');
        $whichYear  = $request->input('which_year');
        $whichMonth = $request->input('which_month');
        $perPage    = $request->input('per_page') ?: 20;
        $list       = Humidity::query()
            ->where('project_id', $projectId)
            ->when($whichYear, function ($query) use ($whichYear) {
                $whichYear = str_replace('年', '', $whichYear);
                return $query->where('which_year', $whichYear);
            })
            ->when($whichMonth, function ($query) use ($whichMonth) {
                if ($whichMonth == '全部') {
                    return $query->where('which_month', '!=', '');
                } else {
                    $whichMonth = str_replace('月', '', $whichMonth);
                    return $query->where('which_month', $whichMonth);
                }
            })
            ->orderByDesc('which_year')
            ->orderBy('which_month')
            ->select('*')
            ->paginate($perPage);

        $data = $list->isNotEmpty() ? $list->toArray() : [];

        return $this->success($data);
    }

    /**
     * 获取年
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2025-01-04 9:59
     */
    public function getYears(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id');
        $years     = Humidity::query()->where('project_id', $projectId)->groupBy('which_year')->pluck('which_year');
        if ($years->isNotEmpty()) {
            $years = $years->toArray();
            foreach ($years as &$year) {
                $year = $year . '年';
            }
        } else {
            $years = ['2021年', '2022年', '2023年', '2024年'];
        }
        return $this->success($years);
    }

    /**
     * 修改仓库
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-29 9:09
     */
    public function updateData(Request $request): JsonResponse
    {
        $params = $request->input('rowData');

        $storeroom              = Humidity::query()->find($params['id']);
        $storeroom->serial_no   = $params['serial_no'];
        $storeroom->which_year  = $params['which_year'];
        $storeroom->which_month = $params['which_month'];
        $storeroom->which_day   = $params['which_day'];
        $storeroom->time_slot   = $params['time_slot'];
        $storeroom->temperature = $params['temperature'];
        $storeroom->humidity    = $params['humidity'];
        $storeroom->remark      = $params['remark'];
        $storeroom->save();

        return $this->success('', '修改成功！');
    }

    /**
     * 导出数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-29 9:07
     */
    public function export(Request $request): JsonResponse
    {
        $projectId    = $request->input('project_id');
        $whichYear    = $request->input('which_year');
        $whichMonth   = $request->input('which_month');
        $yearMonthArr = $this->chunkToMonth($whichYear, $whichMonth);
        $projectName  = Project::query()->where('id', $projectId)->value('title');
        $dirPath      = "excels/{$projectName}{$whichYear}{$whichMonth}温湿度";
        try {
            foreach ($yearMonthArr as $yearMonth) {
                $whichMonth = substr($yearMonth, 7);
                $fileName   = get_valid_path("{$projectName}_温湿度记录表_{$yearMonth}.xlsx");
                $filePath   = "public/$dirPath/$fileName";
                (new HumidityExport($projectId, $whichYear, $whichMonth, $yearMonth))->store($filePath);
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
        CommonService::createDir($dirPath);
        $dirStorage  = "storage/{$dirPath}";
        $downloadUrl = (new DownloadJobService())->mergeExcel($dirStorage);
        $fileInfo    = pathinfo($downloadUrl);
        $data        = [
            'basename'     => $fileInfo['basename'],
            'download_url' => $downloadUrl
        ];
        CommonService::addActionLog("导出档案架布置列表");

        return $this->success($data);
    }

    /**
     * 导出的数据要被分成的年月
     *
     * @param $whichYear
     * @param $whichMonth
     * @return array
     * @author: lxk
     * @date: 2025-01-04 14:19
     */
    public function chunkToMonth($whichYear, $whichMonth): array
    {
        $whichYear = str_replace('年', '', $whichYear);
        $arr       = [];
        if ($whichMonth == '全部') {
            for ($i = 1; $i <= 12; $i++) {
                array_push($arr, $whichYear . '年' . "{$i}月");
            }
        } else {
            array_push($arr, $whichYear . '年' . $whichMonth);
        }
        return $arr;
    }


    /**
     * 导入业务规范等目录
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Exceptions\ApiException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @author: lxk
     * @date: 2024-12-29 9:07
     */
    public function import(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id');

        CommonService::isFileValid($request); //验证文件是否合法
        $importCountKey = get_rand_str('import_humidity_count');
        redis()->setex($importCountKey, 600, 0); //用时最大10分钟
        Excel::import(new HumidityImport($importCountKey, $projectId), $request->file('file'));
        $count = redis()->get($importCountKey) ?: 0;

        CommonService::addActionLog("导入业务规范", "【{$count}】条数据");

        return $this->success('', "成功导入【{$count}】条数据");
    }


    /**
     * 批量软删除，ids可以是以","逗号分割的字符串，也可以是数组形式
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @author: lxk
     * @date: 2024-12-29 9:07
     */
    public function destroyMore(Request $request): JsonResponse
    {
        $projectId  = $request->input('project_id');
        $whichYear  = $request->input('which_year');
        $whichMonth = $request->input('which_month');
        $ids        = $request->input('ids');
        if (!Humidity::destroy(to_array($ids))) {
            return $this->error('删除失败！');
        };
        $redisKey = get_rand_str('del_humidity');
        redis()->set($redisKey, 0); //定义个临时变量
        Humidity::query()
            ->where('project_id', $projectId)
            ->where('which_year', $whichYear)
            ->where('which_month', $whichMonth)
            ->select('id', 'serial_no')
            ->orderBy('serial_no')
            ->orderBy('id')
            ->chunk(100, function ($list) use ($redisKey) {
                foreach ($list as $val) {
                    redis()->incrby($redisKey, 1); //加1
                    $serialNo = redis()->get($redisKey); //获取增加后的值
                    Humidity::query()->where('id', $val->id)->update(['serial_no' => $serialNo]);
                }
            });
        redis()->del($redisKey); //用完删除
        CommonService::addActionLog("删除温湿度记录", "数据ID:{$ids}");

        return $this->success('', '删除成功！');
    }

    /**
     * 新增数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024-12-29 9:08
     */
    public function addData(Request $request): JsonResponse
    {
        $params    = $request->input();
        $thisQuery = Humidity::query()
            ->where('project_id', $params['project_id']);
        if (request()->filled('selectIds')) { //视为插入一行，插入到被选行的上方，然后更新当前案卷下的卷内序号
            $selectIds = to_array($params['selectIds']); //id 为一个或多个，
            $serialNo  = Humidity::query()->whereIn('id', $selectIds)->min('serial_no'); //获取选择里面的最小值
            $thisQuery->where('serial_no', '>=', $serialNo)->increment('serial_no'); //把序号大于当前的那些数据增加
        } else { //获取本案卷最大的序号再 + 1
            $info     = $thisQuery->latest('serial_no')->select('serial_no')->first();
            $serialNo = $info ? $info->serial_no + 1 : 1;
        }
        $batchData['project_id'] = $params['project_id'];
        $batchData['serial_no']  = $serialNo;
        Humidity::query()->insert($batchData);

        $msg = request()->filled('selectIds') ? "成功插入1条数据" : "成功新增1条数据";

        return $this->success('', $msg);
    }

}
